package com.example.controller;

import com.example.dto.LoginRequest;
import com.example.dto.RegisterRequest;
import com.example.service.CaptchaService;
import com.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    private static final Logger log = LoggerFactory.getLogger(AuthController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CaptchaService captchaService;

    @GetMapping("/captcha")
    public ResponseEntity<Map<String, String>> getCaptcha(
            @RequestParam(required = false, defaultValue = "MATH") String type
    ) {
        log.info("获取验证码，请求类型: {}", type);
        try {
            CaptchaService.CaptchaType captchaType = CaptchaService.CaptchaType.valueOf(type.toUpperCase());
            Map<String, String> captcha = captchaService.generateCaptcha(captchaType);
            log.info("生成验证码成功，类型: {}, ID: {}", captchaType, captcha.get("captchaId"));
            return ResponseEntity.ok(captcha);
        } catch (IllegalArgumentException e) {
            // 如果提供的类型无效，默认使用数学验证码
            log.warn("无效的验证码类型: {}，使用默认数学验证码", type);
            Map<String, String> captcha = captchaService.generateCaptcha(CaptchaService.CaptchaType.MATH);
            log.info("生成验证码成功，类型: MATH, ID: {}", captcha.get("captchaId"));
            return ResponseEntity.ok(captcha);
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        log.info("用户登录请求，用户名: {}, 验证码ID: {}", request.getUsername(), request.getCaptchaId());
        // 验证验证码
        if (!captchaService.validateCaptcha(request.getCaptchaId(), request.getCaptcha())) {
            log.warn("验证码验证失败，用户名: {}, 验证码ID: {}", request.getUsername(), request.getCaptchaId());
            Map<String, String> res = new HashMap<>();
            res.put("message", "验证码错误，请重新输入");
            return ResponseEntity.badRequest().body(res);
        }

        try {
            Map<String, Object> result = userService.login(request.getUsername(), request.getPassword());
            log.info("用户登录成功，用户名: {}", request.getUsername());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("用户登录失败，用户名: {}", request.getUsername(), e);
            Map<String, String> res = new HashMap<>();
            res.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(res);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
        log.info("用户注册请求，用户名: {}", request.getUsername());
        try {
            userService.register(request);
            log.info("用户注册成功，用户名: {}", request.getUsername());
            Map<String, String> response = new HashMap<>();
            response.put("message", "注册成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("用户注册失败，用户名: {}", request.getUsername(), e);
            Map<String, String> res = new HashMap<>();
            res.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(res);
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logout() {
        log.info("用户登出请求");
        try {
            // 简化登出逻辑，无需从token获取用户ID
            log.info("用户登出成功");
            Map<String, String> response = new HashMap<>();
            response.put("message", "登出成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("用户登出失败", e);
            Map<String, String> res = new HashMap<>();
            res.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(res);
        }
    }
} 